package com.turing.common.annotationHandler;

import com.turing.common.annotations.InjectUserId;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

@Component
@Aspect
public class UserIdInjectorHandler {

    @Pointcut("@within(com.turing.common.annotations.EnableUserIdInject)")
    public void addAdvice() {
    }

    @Before("addAdvice()")
    public void interceptor(JoinPoint joinPoint) throws Throwable {

//        System.out.println("in proceeding join point");

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        Field[] fields = joinPoint.getTarget().getClass().getDeclaredFields();

        if (!StringUtils.isEmpty(request.getHeader("userId"))) {
            Integer userId = Integer.valueOf(request.getHeader("userId"));

            for (Field field : fields) {
                InjectUserId injectUserId = field.getAnnotation(InjectUserId.class);
                if (injectUserId != null) {
                    boolean isAcc = field.isAccessible();
                    if (!isAcc) {
                        field.setAccessible(true);
                    }
                    field.set(joinPoint.getTarget(), userId);
                    field.setAccessible(isAcc);
                }
            }
        }

    }

}
